package com.bci.pwtz.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.PdbyqMapper;
import com.bci.pwtz.mysql.model.Pdbyq;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.PdbyqService;

/**
 * 一句话描述 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * TODO 详细描述
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *      TODO 代码使用示例
 * </PRE>
 * <p>
 */
@Service
public class PdbyqServiceImpl implements PdbyqService
{
    private PdbyqMapper objMapper;
    
    private CompanyService companyService;
    
    private BusinessRefService businessRefService;
    
    private static final Logger _logger = Logger.getLogger(PdbyqServiceImpl.class);

    /**
     * @return the objMapper
     */
    public PdbyqMapper getObjMapper()
    {
        return objMapper;
    }

    /**
     * @param objMapper the objMapper to set
     */
    public void setObjMapper(PdbyqMapper objMapper)
    {
        this.objMapper = objMapper;
    }

    /**
     * @return the companyService
     */
    public CompanyService getCompanyService()
    {
        return companyService;
    }

    /**
     * @param companyService the companyService to set
     */
    public void setCompanyService(CompanyService companyService)
    {
        this.companyService = companyService;
    }

    /**
     * @return the businessRefService
     */
   

    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param pdbyq
     * @return
     * @throws PwtzDatabaseException 
     * @see com.bci.pwtz.service.PdbyqService#add(com.bci.pwtz.mysql.model.Pdbyq)
     */
    @Override
    public Pdbyq add(Pdbyq pdbyq) throws PwtzDatabaseException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("add:pdbyq=" + pdbyq.toString());
        }
        if (pdbyq == null)
        {
            if (_logger.isDebugEnabled())
            {
                _logger.debug("add,pdbyq is null");
            }
            return null;
        }else{
//            UUID uuid = UUID.randomUUID();
//            pdbyq.setDeviceid(uuid.toString());
            pdbyq.setCreatedate(new Date());
            pdbyq.setLastmodifiedtime(new Date());
            pdbyq.setStatus(1);
        }
        try
        {
            objMapper.insertSelective(pdbyq);
        }
        catch (DataAccessException _e)
        {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return pdbyq;
    }

    public BusinessRefService getBusinessRefService()
    {
        return businessRefService;
    }

    public void setBusinessRefService(BusinessRefService businessRefService)
    {
        this.businessRefService = businessRefService;
    }

    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param pdbyqId
     * @return
     * @throws PwtzDatabaseException 
     * @see com.bci.pwtz.service.PdbyqService#load(java.lang.Long)
     */
    @Override
    public Pdbyq load(String pdbyqId) throws PwtzDatabaseException
    {
        if (_logger.isInfoEnabled())
        {
            _logger.info("load:pdbyqId=" + pdbyqId);
        }
        Pdbyq pdbyq = null;
        try
        {
            pdbyq = objMapper.selectByPrimaryKey(pdbyqId);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (pdbyq != null)
        {
            _logger.debug("load:result pdbyq=" + pdbyq.toString());
        }
        return pdbyq;
    }

    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param pdbyqId
     * @return
     * @throws PwtzDatabaseException 
     * @see com.bci.pwtz.service.PdbyqService#delete(java.lang.Long)
     */
    @Override
    public int delete(String pdbyqId) throws PwtzDatabaseException, CanNotDeleteException
    {
        int result=0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("delete:pdbyqId=" + pdbyqId);
        }
        try
        {
            boolean bl = businessRefService.canDelete("T_PDBYQ", pdbyqId);
            if(!bl){
                throw new CanNotDeleteException();
            }
            result = objMapper.deleteById(pdbyqId,new Date());
        }
        catch (DataAccessException _e)
        {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param pdbyq
     * @return 
     * @see com.bci.pwtz.service.PdbyqService#updateByPrimaryKey(com.bci.pwtz.mysql.model.Pdbyq)
     */
    @Override
    public int update(Pdbyq pdbyq) throws PwtzDatabaseException
    {
        int result=0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("update:pdbyq=" + pdbyq.toString());
        }
        if (pdbyq == null)
        {
            if (_logger.isDebugEnabled())
            {
                _logger.debug("update,pdbyq is null");
            }
            return 0;
        }else{
            pdbyq.setLastmodifiedtime(new Date());
        }
        try
        {
            pdbyq.setLastmodifiedtime(new Date());
            result = objMapper.updateByPrimaryKeySelective(pdbyq);
        }
        catch (DataAccessException _e)
        {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param devicename
     * @param beginTime
     * @param endTime
     * @param pageSize
     * @param pageNo
     * @return
     * @throws PwtzDatabaseException 
     * @see com.bci.pwtz.service.PdbyqService#findPdbyq(java.lang.String, java.lang.String, java.lang.String, int, int)
     */
    @Override
    public PaginationList<Pdbyq> findPdbyq(String devicename,Long companyid,int portalType, String[] medLineCodes,String beginTime, String endTime, int pageSize, int pageNo) throws PwtzDatabaseException
    {
        PaginationList<Pdbyq> paginationList = new PaginationList<Pdbyq>();
        
        if (_logger.isInfoEnabled())
        {
            _logger.info("findDybx:|devicename=" + devicename+"|beginTime=" + beginTime+"|endTime=" + endTime+"|companyid="+companyid+"|portalType="+portalType+"|medLineCodes="+PwtzUtils.parseCharacterArrayToString(medLineCodes)+"|pageSize="+pageSize+"|pageNo="+pageNo);
        }
        List<Pdbyq> list = null;
        int benginIndex = pageSize * pageNo - pageSize;
        String companyidStr = "";
        String[] companyids=null;
        if(portalType==1){
            companyidStr = companyService.findChildrensId(companyid,null);
            if(companyidStr!=null && companyidStr.length()>0){
                companyidStr= companyidStr.substring(0,companyidStr.length()-1);
                companyids =companyidStr.split(",");
            }
        }
        try
        {
            list = objMapper.selectDeviceList(devicename,companyid,companyids,portalType, medLineCodes,beginTime,endTime,benginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list!=null)
        {
            _logger.debug("findPdbyq:result menu=" + list.toString());
        }
        int totalCount = 0;
        int totalPage =1;
        if(pageSize!=0){
            try
            {
                totalCount = objMapper.selectDeviceCount(devicename,companyid,companyids,portalType,medLineCodes, beginTime,endTime);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public PaginationList<Pdbyq> selectDeviceList(String stationcode, int stationdevicetype, String devicename, Long companyid, int pagesize, int pageno) throws PwtzDatabaseException
    {
        if(_logger.isDebugEnabled()){
            _logger.debug("selectDeviceList : |stationcode="+stationcode+"|stationdevicetype="+stationdevicetype+"|devicename="+devicename+"|companyid="+companyid+"|pagesize="+pagesize+"|pageno="+pageno);
        }
        PaginationList<Pdbyq> paginationList = new PaginationList<Pdbyq>();
        int beginIndex = pagesize * pageno - pagesize;
        List<Pdbyq> list=null;
        try{
            list=objMapper.getDeviceList(stationcode, stationdevicetype, devicename, companyid, beginIndex, pagesize);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        int totalCount = 0;
        int totalPage =1;
        if(pagesize!=0){
            try
            {
                totalCount = objMapper.getDeviceCount(stationcode,stationdevicetype,devicename,companyid);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pagesize == 0 ? totalCount / pagesize : totalCount / pagesize + 1;
        }else{
            pageno=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageno);
        paginationList.setPageSize(pagesize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }
    
    @Override
	public int updateLastSyncDevice(Long companyId, String lastSyncTime)  throws PwtzDatabaseException{
		int result=0;
		try {
			result=objMapper.updateLastSyncDevice(companyId, lastSyncTime);
		} catch (DataAccessException e) {
			_logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
		}
		return result;
	}
	
}
